package com.ITArmy.service.impl;

import com.ITArmy.beans.*;
import com.ITArmy.beans.Shows.CommentMessage;
import com.ITArmy.beans.Shows.ReadBlog;
import com.ITArmy.beans.Shows.ReplyMessage;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.dao.*;
import com.ITArmy.service.BlogService;
import com.ITArmy.service.CommentService;
import com.ITArmy.service.ReplyService;
import com.ITArmy.service.UserService;
import com.ITArmy.util.CheckMessage;
import com.ITArmy.util.GetUserSession;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    GetUserSession getUserSession = new GetUserSession();
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    PraiseMapper praiseMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CommentService commentService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ReplyMapper replyMapper;
    @Autowired
    UserService userService;
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    ReplyService replyService;
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    CollectionsMapper collectionsMapper;
    @Autowired
    FocusMapper focusMapper;


    /**
     * 新增博客信息
     */
    @Override
    public ServerResponse addBlogByBack(Blog blog) {
        int resultCount = blogMapper.insertSelective(blog);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "添加成功", "添加失败");
    }

    /**
     * 删除博客信息
     */
    @Override
    public ServerResponse deleteBlogById(Long id) {
        int resultCount = blogMapper.deleteByPrimaryKey(id);
        if (resultCount == 1) {
            //删除博客id对应的所有收藏信息
            collectionsMapper.deleteCollectionByBid(id);
            //查找博客id对应的所有评论信息
            List<Comment> comments = commentMapper.findCommentByBid(id);
            //判断是否有评论
            if (comments != null) {
                //查找与评论信息相关的回复信息
                for (int i = 0; i < comments.size(); i++) {
                    List<Reply> replies = replyMapper.selectAllReply(comments.get(i).getcId());
                    //判断评论是否有回复
                    if (replies != null) {
                        for (int j = 0; j < replies.size(); j++) {
                            //删除与回复有关的所有消息
                            messageMapper.deleteMessageByChid(replies.get(i).getrId());
                        }
                        //删除与评论信息相关的所有回复信息
                        replyMapper.deleteReplyByCid(comments.get(i).getcId());
                    }
                    //删除与评论信息相关对应的消息
                    messageMapper.deleteMessageByCid(comments.get(i).getcId());
                }
                //删除博客id对应的所有评论信息
                commentMapper.deleteCommentByBid(id);
            }
            //删除博客id对应的所有点赞信息
            praiseMapper.deletePraiseByBid(id);
        }
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "删除成功", "删除失败");


        // ArrayList list =(ArrayList<Long>)id;
        // if (list.size() > 1) {
        //     //进行批量删除
        //     int resultCount = 0;
        //     for (int i = 0; i < list.size() - 1; i++) {
        //         int Count = blogMapper.deleteByPrimaryKey(list.get(i));
        //         resultCount += Count;
        //     }
        //     if (resultCount > 0) {
        //         return ServerResponse.createBySuccess("您一共删除" + resultCount + "篇博客");
        //     }
        //     return ServerResponse.createByErrorMesage("删除失败...");
        // }
        //  return ServerResponse.createBySuccess(blogMapper.deleteByPrimaryKey(id));
    }

    /**
     * 批量删除博客
     */
    @Override
    public ServerResponse deleteManyBlogByIds(String[] ids) {
        int resultCount = 0;
        for (int i = 0; i < ids.length; i++) {
            deleteBlogById(Long.parseLong(ids[i]));
            resultCount++;
        }
        if (resultCount == ids.length - 1) {
            return ServerResponse.createBySuccessMessage("删除成功");
        } else {
            return ServerResponse.createByErrorMesage("删除失败");
        }
        //int resultCount = blogMapper.deleteManyBlogByIds(ids);
        //CheckMessage check = new CheckMessage();
        //return check.getMessage(resultCount, "删除成功", "删除失败");
    }

    /**
     * 遍历博客
     */
    @Override
    public List<Blog> findAllBlog() {
        List<Blog> blogs = blogMapper.findAllBlog();
        return blogs;
    }

    /**
     * 修改博客
     */
    @Override
    public ServerResponse updateBlog(Blog blog) {
        int resultCount = blogMapper.updateByPrimaryKeySelective(blog);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "修改信息成功", "修改信息失败");
    }

    /**
     * 根据博客标题模糊搜索
     */
    @Override
    public ServerResponse findBlogByTitle(String title) {
        //判断搜索内容是否为空
        List<Blog> blogs = blogMapper.findBlogByTitle(title);
        if (blogs != null) {
            return ServerResponse.createBySuccess(blogs);
        } else {
            return ServerResponse.createByErrorMesage("无相关信息");
        }
    }

    /**
     * 根据博客类型搜索
     */
    @Override
    public List<ReadBlog> findBlogByType(Integer tid) {
        //判断搜索内容是否为空
        List<ReadBlog> readBlogs = new ArrayList<>();
        List<Blog> blogs = blogMapper.findBlogByType(tid);
        if (blogs == null) {
            return readBlogs;
        }

        for (int i = 0; i < blogs.size(); i++) {
            ReadBlog readBlog = new ReadBlog();
            readBlog.setBlog(blogs.get(i));
            readBlog.setUser(userMapper.selectByPrimaryKey(blogs.get(i).getuId()));
            //获取点赞量
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(blogs.get(i).getbId()).size());
            //获取评论量

            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(blogs.get(i).getuId()).size());
            //获取博客类型
            typeMapper.selectByPrimaryKey((long) blogs.get(i).gettId());
            readBlogs.add(readBlog);
        }


        return readBlogs;


    }


    /**
     * 通过id查找博客
     */
    @Override
    public ReadBlog findBlogById(Long bid, HttpServletRequest request) {
        ReadBlog readBlog = new ReadBlog();
        Blog blog = blogMapper.selectByPrimaryKey(bid);
        readBlog.setBlog(blog);

        readBlog.setUser(userMapper.selectByPrimaryKey(readBlog.getBlog().getuId()));
        //点赞量
        List<Praise> praises = praiseMapper.selectBlogPraiseCount(bid);
        readBlog.setLikeNumber(praises.size());
        //评论量
        List<Comment> comments = commentMapper.findCommentByBlogId(bid);
        readBlog.setCommentNumber(comments.size());
        //进行显示是否点赞过这个博客
        readBlog.setLike(false);
        Praise praise = praiseMapper.selectPraise(getUserSession.getUser(request).getuId(), blog.getbId());
        if (praise != null) {
            readBlog.setLike(true);
            System.out.println("点赞过...");
        }
        //显示是否关注过作者
        readBlog.setLikeUser(false);
        if (focusMapper.checkIsFocus(blog.getuId(), getUserSession.getUser(request).getuId()) != null) {
            System.out.println("关注过啊");
            readBlog.setLikeUser(true);
        }
        //显示是否收藏过这篇博客
        readBlog.setCollection(false);
        if (collectionsMapper.checkCollection(getUserSession.getUser(request).getuId(), bid) > 0) {
            readBlog.setCollection(true);
        }
        readBlog.setCollection(false);
        if (collectionsMapper.checkCollection(getUserSession.getUser(request).getuId(), bid) > 0) {
            readBlog.setCollection(true);
        }
        return readBlog;
    }

    /**
     * 设置为推荐
     */
    @Override
    public ServerResponse recommend(Long id) {
        int resultCount = blogMapper.recommend(id);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "推荐成功", "推荐失败");
    }

    /**
     * 取消推荐
     */
    @Override
    public ServerResponse unrecommend(Long id) {
        int resultCount = blogMapper.unrecommend(id);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "取消推荐成功", "取消推荐失败");
    }

    /**
     * 遍历推荐博客
     */
    @Override
    public ServerResponse recommendList() {
        //判断内容是否为空
        List<Blog> blogs = blogMapper.recommendList();
        if (blogs != null) {
            return ServerResponse.createBySuccess(blogs);
        } else {
            return ServerResponse.createByErrorMesage("内容为空");
        }
    }

    /**
     * 根据博客类型遍历推荐博客
     */
    @Override
    public ServerResponse findRecommendByType(Integer tid) {
        //判断内容是否为空
        List<Blog> blogs = blogMapper.findRecommendByType(tid);
        if (blogs != null) {
            return ServerResponse.createBySuccess(blogs);
        } else {
            return ServerResponse.createByErrorMesage("内容为空");
        }
    }

    /**
     * 显示用户喜欢的博客
     */
    @Override
    public List<ReadBlog> findLikeBlog(HttpServletRequest request) {
        User user = getUserSession.getUser(request);
        List<Praise> praises = praiseMapper.selectAllLikeByUid(user.getuId());
        List<ReadBlog> likeBlogs = new ArrayList<>();
        if (praises.size() == 0) {
            return likeBlogs;
        }
        for (int i = 0; i < praises.size(); i++) {
            ReadBlog readBlog = new ReadBlog();
            //博客信息
            readBlog.setBlog(blogMapper.selectByPrimaryKey(praises.get(i).getbId()));
            //用户信息
            readBlog.setUser(userMapper.selectByPrimaryKey(readBlog.getBlog().getuId()));
            //点赞数量
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(readBlog.getBlog().getbId()).size());
            //评论数量
            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(readBlog.getBlog().getuId()).size());
            likeBlogs.add(readBlog);
        }
        return likeBlogs;
    }

    /**
     * 根据id显示用户发表的所有博客
     */
    @Override
    public ServerResponse getPublishCount(HttpServletRequest request) {
        User user = getUserSession.getUser(request);
        List<Blog> blogs = blogMapper.selectPublishCount(user.getuId());
        if (blogs.size() < 1) {
            return ServerResponse.createByErrorMesage("您还没发表过博客...");
        } else {
            return ServerResponse.createBySuccess("获取成功...", blogs);
        }

    }


    /**
     * 用户发布博客
     */
    @Override
    public ServerResponse addBlog(HttpServletRequest request, Blog blog) {
        blog.setbRecommend("1");
        blog.setbTime(new Date());
        blog.setuId(getUserSession.getUser(request).getuId());
        int resultCount = blogMapper.insertSelective(blog);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "发布成功", "发布失败");
    }

    /**
     * 获取关于评论的所有消息
     */
    @Override
    public List<CommentMessage> getBlogCommentMessage(long blogId) {
        //查询关于博客的所有评论信息
        List<Comment> commons = commentService.findCommentByBlogId(blogId);
        //创建集合储存封装的评论信息
        List<CommentMessage> commentMessages = new ArrayList<>();
        if (commons == null) {
            //如果这个博客没有评论，返回一个空的集合
            return commentMessages;
        }
        for (int i = 0; i < commons.size(); i++) {
            CommentMessage commentMessage = new CommentMessage();
            //将评论者储存到封装的对象中
            commentMessage.setUser(userMapper.selectByPrimaryKey(commons.get(i).getuId()));
            //将评论的具体信息储存到封装对象中
            commentMessage.setComment(commons.get(i));
            //将博客信息储存到封装对象中
            commentMessage.setBlog(blogMapper.selectByPrimaryKey(commons.get(i).getbId()));
            //获取这条评论的所有回复
            commentMessage.setReplyMessage(replyService.getReplyMessageByCid(commons.get(i).getcId()));
            //将数据添加到集合中
            commentMessages.add(commentMessage);
        }

        return commentMessages;
    }

    /**
     * 通过类型id查找博客
     */
    @Override
    public ServerResponse findByType(Integer tid) {
        List<Blog> blogs = blogMapper.findBlogByType(tid);
        if (blogs != null) {
            return ServerResponse.createBySuccess(blogs);
        } else {
            return ServerResponse.createByErrorMesage("无相关内容");
        }
    }

    //根据评论的id获取所有的回复信息
    @Override
    public List<ReplyMessage> getReplyMessageByCid(long cId) {
        List<Reply> replies = replyMapper.selectAllReply(cId);
        List<ReplyMessage> replyMessages = new ArrayList<>();
        if (replies == null) {
            return replyMessages;
        }
        //进行封装所有有关回复的信息
        for (int i = 0; i < replies.size(); i++) {
            ReplyMessage replyMessage = new ReplyMessage();
            //回复的具体信息
            replyMessage.setReply(replies.get(i));
            //回复人的信息
            userMapper.selectByPrimaryKey(replies.get(i).getrUId());
            //被回复人的信息
            userMapper.selectByPrimaryKey(replies.get(i).gettUId());
            replyMessages.add(replyMessage);
        }
        return replyMessages;
    }

    @Override
    public List<ReadBlog> getAllReadBlogs(HttpServletRequest request) {
        List<Blog> blogs = blogMapper.recommendList();
        List<ReadBlog> recommendBlog = new ArrayList();
        for (int i = 0; i < blogs.size(); i++) {
            ReadBlog readBlog = new ReadBlog();
            //博客信息
            readBlog.setBlog(blogs.get(i));
            //用户信息
            readBlog.setUser(userMapper.selectByPrimaryKey(blogs.get(i).getuId()));
            //点赞数量
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(blogs.get(i).getbId()).size());
            //评论数量
            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(blogs.get(i).getbId()).size());
            recommendBlog.add(readBlog);
        }
        return recommendBlog;
    }

    @Override
    public List<ReadBlog> getPersonPublicBlog(long uId) {
        List<Blog> blogs = blogMapper.selectPublishCount(uId);
        List<ReadBlog> recommendBlog = new ArrayList();
        for (int i = 0; i < blogs.size(); i++) {
            ReadBlog readBlog = new ReadBlog();
            //博客信息
            readBlog.setBlog(blogs.get(i));
            //用户信息
            readBlog.setUser(userMapper.selectByPrimaryKey(blogs.get(i).getuId()));
            //点赞数量
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(blogs.get(i).getbId()).size());
            //评论数量
            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(blogs.get(i).getbId()).size());
            recommendBlog.add(readBlog);
        }
        return recommendBlog;
    }

}
